<template>
    <view class="gift-purchase">
      <view class="header">
        <view><uni-status-bar></uni-status-bar></view>
  
        <view class="search-box flex-cn">
          <view class="navbar-left flex-cn" style="flex: 1" @click="backHome">
            <view
              style="width: 100rpx; text-align: center"
              class="qh-rt-single qh-rt-zuo-zuo navbar-back-icon"
            >
            </view>
          </view>
  
          <view
              style="
                  height: 80rpx;
                  line-height: 80rpx;
                  font-size: 36rpx;
                  font-family: '.PingFang SC, PingFang SC';
                  display: flex;
                  justify-content: center;
                  align-content: center;
                  flex: 1;
                  color: #000;
                  font-weight: 600;
              "
              >
              时福礼品卡
              </view>
              <view style="width: 320rpx; flex: 1"></view>
          </view>   
      </view> 

      <view style="margin-top: 40rpx;" >
        <scroll-view class="home-icon" :scroll-left="scrollLeft" scroll-x="true" ref="scroll" style="white-space: nowrap" @scroll="onScroll">
        <view style="margin-left: 40rpx;">
          <block v-for="(item,index) in priceList.price" :key="index">
            <view :id="'item-' + index" class="min-icon">
              <text>￥{{ item.money }}</text>
              <image :src="priceList.img_url" alt="" class="icon-image" />
            </view>
          </block>
        </view>
      </scroll-view>
    </view>

        <view class="explain">
            <text class="explain_title">时福礼品卡</text>
            <view class="explain_content">
                {{ priceList.notes }}
            </view>
        </view>

        <view class="limit">
            <text >选择面额:</text>
            <view style="display: flex;flex-wrap: wrap;margin-top: 16rpx;"> 
              <block v-for="(item,index) in priceList.price " :key="index" >
                <view class="limit_content" @click="handlerMoney(item,index)"   :style="{ 'border': selected.includes(index) ? '2rpx solid #FFB73F' : '2rpx solid #F5F4F6' , 'background-color':  selected.includes(index)  ? '#F4FFF2' : '#F5F4F6'}"   >
                    <view>￥{{ item.money }}</view>
                    <view :style="{ 'border-top': selected.includes(index)  ? '1px solid #FFB73F' : '1px solid #E8E8E8' }">
                      <text
                      @click.stop="reduceNum(item,index)"
                        class="icontext qh-rt-single qh-rt-a-zu4424 car-num-icon reduce"
                        v-if="item.cardNum >0"
                      ></text>

                      <text v-if="item.cardNum >0"   style="color: #FFB73F;" class="num_text">{{ item.cardNum }}</text>

                      <text
                        @click.stop="addCardNum(item,index)"
                        class="icontext qh-rt-single qh-rt-a-zu4423 car-num-icon add"
                      ></text>
                  </view>
                </view>
              </block>
            </view>
        </view>


        <view class="limit_bottom" @click="confirmPay">
            <view >
              <text class="bottom_title" >确认支付 ¥{{totalMoney}}（{{totalCard}}张）</text>
            </view>
        </view>
  
    
      
    </view>
  </template>
  
  <script>
export default {
  data() {
    // 10,20,30,50,100,200,500,1000,2000
    return {
      selected: [],
      currentId: 0,
      animationData: null,
      scrollLeft: null,
      limit_list: [
        { money: 10 , },
        { money: 20 },
        { money: 30 },
        { money: 50 },
        { money: 100 },
        { money: 200 },
        { money: 500 },
        { money: 1000 },
        { money: 2000 },
        { money: 20000 },
      ], //面额数组
      buyId:null,

      cardNum:0,
      priceList:[],//面额数据
      totalMoney:0, //总金额
      totalCard:0,  //总卡数
      initialScrollLeft:0,
      cover_id:null,  //封面ID
      gift_id:null,  //礼品ID
      animation:false
    };
  },

  onLoad(options){
    this.buyId  = options.id  

    if(this.buyId){

       this.$request(
			  "/SmallProgramApi/ShiFu/getGiftCardDetail",
			  { store_id: this.$store.mallStoreId  ,id: this.buyId}
		  ).then((result)=>{
        console.log(result, 'resultresult')
           
        this.priceList = result.data
        this.cover_id = result.data.cover_id
        this.gift_id = result.data.id
        this.priceList.price = this.priceList.price.map(item => {
          return {
            ...item,  // 使用扩展操作符来深拷贝原来的对象
            cardNum: 0  // 添加新的 cardNum 属性
          };
        });
        console.log(this.priceList   , 'this.priceList this.priceList this.priceList ')
      })
    }


  },
  methods: {
  

    // 添加 
    addCardNum(item,index){
      if(item.cardNum > item.less_num) {
        uni.showToast({
					title: '不能大于剩余数量卡',
					icon: 'none'
				})  
        return
      }

      this.selected.push(index);
      this.selected= [...new Set([...this.selected, index])]
      item.cardNum++
    
      //总卡数
      this.totalCard = this.priceList.price.reduce((total, val) => total + val.cardNum, 0);
      
      // 计算总金额
      this.totalMoney = this.priceList.price.reduce((total, val) => total + val.cardNum * val.money, 0);  
      this.totalMoney  =  this.totalMoney.toFixed(2)
    },

    // 减少
    reduceNum(item,index){
      if(item.cardNum > 0) {
        item.cardNum--;
        //样式去除
        if(item.cardNum === 0) {
          const selectedIndex = this.selected.indexOf(index);
          if (selectedIndex > -1) {
            this.selected.splice(selectedIndex, 1);
          } 
        }
          if(this.totalCard > 0 && this.totalMoney > 0){
            // 总卡数
            this.totalCard--
            // 计算总金额 
            this.totalMoney = (( this.totalMoney * 100 )   - (item.money * 100 ) ) / 100 
            this.totalMoney  =  this.totalMoney.toFixed(2)
          }

      }
    },

    //后退
    backHome() {
      uni.navigateBack();
    },

    onScroll(e) {
      this.initialScrollLeft = e.target.scrollLeft;  
    },

    //点击滚动
    handlerMoney(item,index) {
      if(item.cardNum == 0){
        item.cardNum++
        //总卡数
      this.totalCard = this.priceList.price.reduce((total, val) => total + val.cardNum, 0);
      
      // 计算总金额
      this.totalMoney = this.priceList.price.reduce((total, val) => total + val.cardNum * val.money, 0);  
      this.totalMoney  =  this.totalMoney.toFixed(2)
      //去除小数点 this.totalMoney = this.priceList.price.reduce((total, val) => total + Math.floor(val.cardNum * val.money), 0);
      }
      this.selected.push(index);
      this.selected= [...new Set([...this.selected, index])]
      // const selectedIndex = this.selected.indexOf(index);
      // if (selectedIndex > -1) {
      //   this.selected.splice(selectedIndex, 1);
      // } else {
      //   this.selected.push(index);
      // }

          this.currentId = index;  //用于来定位元素 
          var that = this;  
          if (!this.animation) {
            this.animation = true;
            uni.createSelectorQuery().select(`#item-${index}`).boundingClientRect(rect => {
              const windowWidth = uni.getSystemInfoSync().windowWidth;
              const scrollLeft = rect.left - windowWidth / 2 + rect.width / 2;
              let targetScrollLeft = this.initialScrollLeft + scrollLeft;

              let interval = setInterval(() => {
                if (Math.abs(targetScrollLeft - that.scrollLeft) <= 1) {
                  that.scrollLeft = targetScrollLeft;
                  clearInterval(interval);
                  interval = null;
                  this.animation = false; // 动画结束，修改 animation状态
                } else {
                  that.scrollLeft += (targetScrollLeft - that.scrollLeft) * 0.1;
                }
              }, 10);
            }).exec();
          }
    },

    confirmPay(){
      // 过滤一下
      let filtered = this.priceList.price.filter(item => item.cardNum >= 1);
      let price_data = filtered.map(item => ({
          price_id: item.id,
          buy_num: item.cardNum,
          money: item.money,
          img_url: this.priceList.img_url 
      }));

      let id = this.priceList.id;

      console.log(price_data);

      if (this.priceList.gift_card_class_name === '实物卡') {
        let obj = { store_id: this.$store.mallStoreId  ,
                    cover_id: this.cover_id,  //封面ID
                    id:this.gift_id,   //礼品卡ID
                    buy_info:JSON.stringify(price_data)
                  }
        if(this.selected.length <= 0) return 
          uni.navigateTo({
              url: `/pages/mer/tabbar/entityPay/entityPay?id=${id}&payList=${JSON.stringify(price_data)}&totalMoney=${this.totalMoney}&payObj=${JSON.stringify(obj)}`
              // 使用字符串模板语法，并将 price_data 转换为字符串格式
          });

          return
      }
      

      console.log(this.gift_id,this.cover_id  ,price_data   ,'1111111111111111111111')
    
      this.$request(
			  "/SmallProgramApi/ShiFu/createOrder_v2",
			  { store_id: this.$store.mallStoreId  ,
          cover_id: this.cover_id,  //封面ID
          id:this.gift_id,   //礼品卡ID
          buy_info:JSON.stringify(price_data)
        }
		  ).then((ret)=>{
        uni.showToast({
          title: ret.msg,
          icon: "none",
        })

        if (ret.status == 1) {
            // #ifdef MP-WEIXIN
            uni.requestPayment({
              timeStamp: ret.payData.timeStamp,
              nonceStr: ret.payData.nonceStr,
              //字符串随机数
              package: ret.payData.package,
              signType: ret.payData.signType,
              paySign: ret.payData.paySign,
              success: (re)=> {
                if (re.errMsg == 'requestPayment:ok') {
                  // 下单
                  uni.showLoading({
                    title: '查询中...',
                    mask: true
                  });
                  this.searchOrder(ret.order_id,
                    0); //查询订单
                } 
              }
            });
            // #endif
        }
      })
    },

    searchOrder(order_no, count) {
        const that = this;
        this.$request( '/SmallProgramApi/GiftCard/searchOrder' , {order_id: order_no}  ).then((res)=>{
          if (res.status === 1) {
              uni.hideLoading();
              uni.showToast({
                title: '等待支付',
                duration: 1000,
                mask: true,
                success() {
                  // uni.navigateTo({
                  //   url: '/pages/mine/gift_card/gift_card?id=' + order_no
                  // });
                  uni.navigateTo({
                    // url: '/pages/mine/gift_mycard/gift_mycard'
                    url:'/pages/mer/tabbar/my_gift_mycard/my_gift_mycard'
                  });
                }
              });
            } else if (res.status === 2) {
              count++;

              if (count > 10) {
             
                uni.hideLoading();
                uni.showModal({
                  title: '提醒',
                  content: res.msg,
                  showCancel: false,
                  confirmColor: '#ff5c6d'
                });
              } else {
                setTimeout(() => {
                  that.searchOrder(order_no, count);
                }, 1000);
              }
            } else {
          
              uni.hideLoading();
              uni.showModal({
                title: '提醒',
                content: res.msg,
                showCancel: false,
                confirmColor: '#ff5c6d'
              });
            }
        })
     
     }



      
  },
};
</script>
  <style>
@import "./gift_mycard.scss";
</style>
  